package MsgSystem;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

//This class implements the send connections and sends the file to the destination
public class SendFilesClass {

    private static final Log LOGGER = LogFactory.getLog("common");
    ImpInstantMessage itm = null;
    ImpGenericMessage igm = null;
    ImpUserContent iuc = null;

    public SendFilesClass(ImpInstantMessage itm, ImpGenericMessage igm) {
        this.itm = itm;
        this.igm = igm;
    }

    public void send() {
        FileTransferManager manager = new FileTransferManager(itm.connect);
        FileTransferNegotiator.setServiceEnabled(itm.connect, true);
        OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(igm.getDestination());
        LOGGER.info("Connection created");
        iuc = igm.getUserContent();
        File file = new File("outcoming", iuc.getRequest() + ".jpg");



        if (file.canRead()) {
            LOGGER.info("SE PUEDE LEER!!");
        }
        if (file.exists()) {
            LOGGER.info("EL FICHERO EXISTE!!");
        }
        if (file.isFile()) {
            LOGGER.info("EL FICHERO ES UN FICHERO!");
        }
        if (file.canWrite()) {
            LOGGER.info("EL FICHERO SE PUEDE ESCRIBIR!!");
        } else {
            LOGGER.info("ERROR FILE");
        }


        File file2 = new File(file.getAbsolutePath());
        LOGGER.info("The absolute path of the file is: " + file2.getAbsolutePath());
        try {
            transfer.sendFile(file2, file2.getName());
            LOGGER.info("File " + file2.getName() + " is sending to " + igm.getDestination());
        } catch (XMPPException ex) {
            LOGGER.info("An error has been ocurred sending the file");
            Logger.getLogger(ImpListener.class.getName()).log(Level.SEVERE, null, ex);
        }
        while (!transfer.isDone()) {
            if (transfer.getStatus().equals(FileTransfer.Status.error)) {
                LOGGER.info("ERROR!!! " + transfer.getError());
            } else {
                LOGGER.info(transfer.getStatus());
                LOGGER.info(transfer.getProgress() * 100);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ReceiveMessages.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
